package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.entity.PageResult;
import com.qingcheng.entity.Result;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.pojo.order.OrderItem;
import com.qingcheng.service.order.OrderItemService;
import com.qingcheng.service.order.OrderService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: create by Yao ZhongZhe
 * @date:2019/7/28
 * @version: v1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;

    @Reference
    private OrderItemService orderItemService;

    @GetMapping("/findOrderPage")
    public PageResult<Object> findOrderPage(int page, int size){
        String username= SecurityContextHolder.getContext().getAuthentication().getName();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("username",username);
        PageResult<Order> orderPage = orderService.findPage(map1,page, size);
        List<Order> orderList = orderPage.getRows();
        List arrayList = new ArrayList();
        for (Order order : orderList) {
            Map<String,Object> map = new HashMap();
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("orderId",order.getId());
            List<OrderItem> orderItemList = orderItemService.findList(searchMap);
            map.put("order",order);
            map.put("orderItemList",orderItemList);
            arrayList.add(map);
        }
        PageResult<Object> result = new PageResult<>();
        result.setRows(arrayList);
        result.setTotal(orderPage.getTotal());
        return  result;
    }

    @GetMapping("/findOrderItemById")
    public OrderItem findOrderItemById(String id){
        OrderItem orderItem = orderItemService.findById(id);
        return  orderItem;
    }

    @GetMapping("/delete")
    public Result delete(String orderId, String orderItemId){
        System.out.println(orderId);
        System.out.println(orderItemId);
        orderItemService.delete(orderItemId);
        OrderItem orderItem = new OrderItem();
        Map<String,Object> map=new HashMap<>();
        map.put("orderId",orderId);
        List<OrderItem> list = orderItemService.findList(map);
        if (list.size()==0){
            Order order = new Order();
            order.setId(orderId);
            order.setIsDelete("1");
            orderService.update(order);
        }
        return new Result();
    }
}
